<template>
  <div>
    <h2>-----------App内容----------</h2>
    <h2>{{ $store.state.counter }}</h2>
    <button @click="addition">+</button>
    <button @click="subtraction">-</button>
    <button @click="addCount(5)">+</button>
    <button @click="addCount(10)">+</button>
    <h2>-------------App内容：getter相关信息</h2>
    <h2>{{ $store.state.counter * $store.state.counter }}</h2>
    <h2>{{ $store.getters.powerCounter }}</h2>

  </div>
</template>

<script>
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
const store = new Vuex.store({
  // 状态， 就是需要全局能被使用的数据(响应式)
  state: {
    counter: 1000,
    students: [
      {id: 1, name: 'lwx', age: 15},
      {id: 2, name: 'ddd', age: 16},
      {id: 3, name: 'lff', age: 14},
      {id: 4, name: 'lfr', age: 18},
    ]
  },
  // 每一次状态改变都经过他才会有记录
  mutations: {
    // increment 事件类型  (state) {state.counter++},回调
    increment(state) {
      state.counter++
    },
    decrement() {
      state.counter--
    },
    incrementCount(state, count) {
      state.counter += count
      // 对象提交风格
      state.counter += payload.count

    },
    incrementStu(state, stu) {
      this.state.students.push(stu)
    },update (state) {
      // 响应
      Vue.set(state.info, 'address', '罗山')
      // 不响应
      delete state.info.age
      // 响应
      Vue.delete(state.info, 'age')
    }
  },
  // 异步处理，有网络请求会通过action
  actions: {},
  // 类似于computed属性
  getters: {
    powerCounter(state) {
      return state.counter * state.counter
    },
    more15stu(state) {
      return state.students.filter(s => s.age > 15)
    },
    more15stulenth(state, getters) {
      return getters.more15stulenth.length
    }
  }
})

export default {
  name: "01-vuex基础",
  data() {
    return {
      message: '我是App组件'
    }
  },
  methods: {
    addition() {
      this.$store.commit('increment')
    },
    subtraction() {
      this.$store.commit('decrement')
    },
    // payload 负载
    addCount(count) {
      // 普通提交风格
      this.$store.commit('incrementCount', count)
      // 特殊提交风格
      this.$store.commit({
        type: 'incrementCount',
        count
      })
    },
    addStu() {
      const stu = {id: 5, nane: 'frr', age: 9}
      this.$store.state.commit('incrementStu', stu)
    }
  },
  computed: {
    more15stu() {
      return this.$store.state.students.filter(s => s.age > 15)
    }
  }
}
</script>

<style scoped>

</style>
